package com.google.gdata.client.douban;

import java.io.IOException;
import java.net.URL;
import java.util.Map;

import com.google.gdata.client.Service.GDataRequest;
import com.google.gdata.client.http.GoogleGDataRequest;
import com.google.gdata.client.http.HttpAuthToken;
import com.google.gdata.client.http.HttpUrlConnectionSource;
import com.google.gdata.util.ContentType;
import com.google.gdata.util.ServiceException;

public class DoubanGDataRequest extends GoogleGDataRequest {

	private static final String OK_CONTENT_LENGTH = "2";

	protected DoubanGDataRequest(RequestType type, URL requestUrl,
			ContentType contentType, HttpAuthToken authToken,
			Map<String, String> headerMap,
			Map<String, String> privateHeaderMap,
			HttpUrlConnectionSource connectionSource) throws IOException {
		super(type, requestUrl, contentType, authToken, headerMap,
				privateHeaderMap, connectionSource);
	}

	public ContentType getResponseContentType() {

		if (!executed) {
			throw new IllegalStateException(
					"Must call execute() before attempting to read response");
		}
		String value = httpConn.getHeaderField("Content-Type");
		if (value == null) {
			return null;
		}
		if (value.equals("text/xml; charset=utf-8")) {
			String contentLength = this.getResponseHeader("Content-Length");
			if (OK_CONTENT_LENGTH.equals(contentLength)) {
				return ContentType.TEXT_PLAIN;
			} else {
				return ContentType.ATOM;
			}
		}
		return new ContentType(value);
	}
	
	public static class Factory extends GoogleGDataRequest.Factory {
	    @Override
	    protected GDataRequest createRequest(RequestType type,
	        URL requestUrl, ContentType contentType)
	        throws IOException, ServiceException {
	      return new DoubanGDataRequest(type, requestUrl, contentType, authToken, 
	          headerMap, privateHeaderMap, connectionSource);
	    }
	  }
}
